package com.joysuch.wwyt.core.quartz;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.joysuch.wwyt.core.entity.BaseAttachmentRepo;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.FileConvertService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;


/**
 * 异常文件转换pdf处理
 *
 * @author xsx
 * @version 1.0
 * @date 2023/5/12 18:17
 */
@Component
@Slf4j
public class ConvertPdfJob {

    @Autowired
    private FileConvertService fileConvertService;

    @Autowired
    private BaseAttachmentRepositoryService repositoryService;


    @Value("${wwyt.file.upload.dir}")
    private String fileUploadDir;

    @Autowired
    private BaseConfigService configService;

    @Scheduled(cron = "0 0/3 * * * ?")
    public void convertPdf() {
        int retryCount = 5;
        BaseConfig config = configService.findFirstConfig(BaseConfigCodes.RETRYCOUNT);
        if (config != null && StringUtils.isNotBlank(config.getValue())) {
            retryCount = Integer.parseInt(config.getValue());
        }
        BaseAttachmentRepo attachmentRepo = repositoryService.findBaseAttachmentRepo(retryCount);
        if (attachmentRepo != null) {
            String fileName = attachmentRepo.getFingerPrint();
            String extension = FilenameUtils.getExtension(attachmentRepo.getFileName());
            // 避免将文件存储在一个目录下，使用文件名前2个字符作为子文件夹
            String subdir = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
            String dir = fileUploadDir + File.separator + subdir;
//            String relativePath = subdir + "/" + fileName + "." + extension;
            File newFile = new File(dir + File.separator + fileName + "." + extension);
            fileConvertService.convert(attachmentRepo, newFile);
        }
    }


}
